//
//  KRFeedbackViewController.m
//  KEREN
//
//  Created by MW on 2023/4/23.
//

#import "KRFeedbackViewController.h"

@interface KRFeedbackViewController ()<TZImagePickerControllerDelegate,UITextViewDelegate>

@property (nonatomic, strong) UILabel *titLbl;
@property (nonatomic, strong) NSMutableArray *imgArrM;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UITextField *phoneFiled;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, strong) UIView *imagesView;
@property (nonatomic, strong) UILabel *countLbl;
@property (nonatomic, strong) UIView *whireView;
@end

@implementation KRFeedbackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"意见反馈"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //当键盘将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    _whireView = [[UIView alloc] init];
    [self.view addSubview:_whireView];
    _whireView.backgroundColor = Whire_Color;
    //TODO:国际化
    _titLbl = [UILabel setLblText:@"请提供问题截图（0/6）" font:Font(16) withColor:Color_333333 inSubView:_whireView];
    [_titLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.top.offset(16);
    }];
    
    _imagesView = [[UIView alloc] init];
    [_whireView addSubview:_imagesView];
    float imageWidth = (DEVICE_WIDTH - 96) / 3;
    [_imagesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.offset(0);
        make.height.offset(imageWidth);
        make.top.equalTo(_titLbl.mas_bottom).offset(16);
    }];
    
    _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_imagesView addSubview:_addBtn];
    [_addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(imageWidth);
        make.top.offset(0);
        make.left.offset(24);
    }];
    [_addBtn setImage:[UIImage imageNamed:@"image_add"] forState:UIControlStateNormal];
    [_addBtn addTarget:self action:@selector(addImage) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *lineView = [UIView setLineViewWithframe:CGRectZero forinView:_whireView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_imagesView.mas_bottom).offset(16);
        make.height.offset(1);
        make.left.offset(24);
        make.right.offset(-24);
    }];
    
    UILabel *tips = [UILabel setLblText:@"*问题和意见" font:Font(16) withColor:Color_333333 inSubView:_whireView];
    NSAttributedString *showAttString = [NSAttributedString getAttributeWith:@[@"*"] string:@"*问题和意见" Font:Font(16) Color:Color_333333 attributeFont:Font(16) attributeColor:Color_F84553];
    tips.attributedText = showAttString;

    [tips mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_imagesView.mas_bottom).offset(32);
        make.left.offset(24);
    }];
    UIView *textbackView = [[UIView alloc] init];
    [_whireView addSubview:textbackView];
    [textbackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(120);
        make.top.equalTo(tips.mas_bottom).offset(8);
    }];
    textbackView.layer.cornerRadius = 25;
    textbackView.clipsToBounds = YES;
    textbackView.layer.borderWidth = 1;
    textbackView.layer.borderColor = Color_EEEEEE.CGColor;


    _textView = [[UITextView alloc] init];
    _textView.delegate = self;
    
    _textView.textContainerInset = UIEdgeInsetsMake(12, 12, 32, 12);
    [textbackView addSubview:_textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(100);
        make.top.equalTo(tips.mas_bottom).offset(8);
    }];
    _textView.font = Font(14);

    _countLbl = [UILabel setLblText:@"0/500" font:Font(12) withColor:Color_B2B2B2 inSubView:_whireView];
    [_countLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-36);
        make.top.equalTo(_textView.mas_bottom).offset(0);
    }];
//    UIView *phoneLineView = [UIView setLineViewWithframe:CGRectZero forinView:_whireView];
//
//    [phoneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(24);
//        make.right.offset(-24);
//        make.height.offset(1);
//        make.top.equalTo(textbackView.mas_bottom).offset(16);
//    }];
//
//    UILabel *phoneTips = [UILabel setLblText:@"联系方式" font:Font(16) withColor:Black_Color inSubView:_whireView];
//    float tipsWidth = [[NSStringManager shareInstance] measureSinglelineStringWidth:@"联系方式" andFont:Font(16)];
//    [phoneTips mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(24);
//        make.top.equalTo(phoneLineView.mas_bottom).offset(18);
//        make.width.offset(tipsWidth + 2);
//    }];
//    _phoneFiled = [UITextField setFlieldplaceholder:@"" Font:Font(14) borderColor:Color_EEEEEE];
//    _phoneFiled.text = USERINFO.phone;
//    _phoneFiled.keyboardType = UIKeyboardTypeNumberPad;
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
//                                                name:@"UITextFieldTextDidChangeNotification"
//                                              object:_phoneFiled];
//    [_whireView addSubview:_phoneFiled];
//    [_phoneFiled mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(phoneTips.mas_right).offset(10);
//        make.height.offset(48);
//        make.centerY.equalTo(phoneTips);
//        make.right.offset(-24);
//    }];
    //_phoneFiled.enabled = NO;
    [_whireView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(60 + STATUSBAR_HEIGHT);
        make.left.right.offset(0);
        make.bottom.equalTo(_countLbl.mas_bottom).offset(20);
    }];
    
    UIButton *pushBtn = [UIButton setButtonWithTitle:@"提交" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
    [self.view addSubview:pushBtn];
    
    [pushBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(58);
        make.bottom.offset(-BottomSpance_height);
    }];
    [pushBtn addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(uploagImgs) name:IMGSUPLOADFINISH object:nil];
    //Whire_Color
}

- (void)addImage{
    [[FlieUploadManager shareInstance] getossToken];
    TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:6 - self.imgArrM.count delegate:self];
    imagePC.allowTakePicture = YES;
    imagePC.allowTakeVideo = NO;
    imagePC.allowPickingVideo = NO;
    imagePC.allowPickingGif = NO;
    imagePC.showSelectedIndex = YES;
    imagePC.allowPickingOriginalPhoto = YES;//原图
    imagePC.minImagesCount = 0;
    imagePC.showSelectBtn = NO;
    imagePC.allowPreview = YES;
    imagePC.autoSelectCurrentWhenDone = YES;
    imagePC.modalPresentationStyle = 0;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self presentViewController:imagePC animated:YES completion:nil];
    });

}

- (void)push{
    WEAKSELF
    if(_textView.text.length < 1){
        [[KRAlartManager shareInstance] showErrorAlert:@"请填写反馈内容"];
        return;
    }
   // Feedback_create
    if(_imgArrM.count > 0){
        [[FlieUploadManager shareInstance] uploadImagesToOss:_imgArrM type:2];
    }else{
        NSDictionary *parameters = @{@"type":@(1),@"phone":USERINFO.phone,@"details":_textView.text,@"images":@[]};
        [NetworkingTool POST:Feedback_create parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
            if([response[@"code"] intValue] == 0){
                [weakSelf.navigationController popViewControllerAnimated:YES];
                [[KRAlartManager shareInstance] showAlert:@"反馈成功"];
                
            }
        } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
            
        }];
    }
}

- (void)uploagImgs{
    WEAKSELF
    NSDictionary *parameters = @{@"type":@(1),@"phone":USERINFO.phone,@"details":_textView.text,@"images":[FlieUploadManager shareInstance].imgsArrM};
    [NetworkingTool POST:Feedback_create parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [[KRAlartManager shareInstance] showAlert:@"反馈成功"];
            
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];

}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    [[FlieUploadManager shareInstance] getossToken];
    for (UIImage *img in photos) {
        [self.imgArrM addObject:img];
    }
    [self updateImagesView];
}

- (void)updateImagesView{
    if(_imgArrM.count == 6){
        _addBtn.hidden = YES;
    }else{
        _addBtn.hidden = NO;
    }
    float imageWidth = (DEVICE_WIDTH - 96) / 3;

    if(_imgArrM.count > 2){
        [_imagesView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.offset(imageWidth * 2 + 16);
        }];
    }else{
        [_imagesView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.offset(imageWidth);
        }];
    }
    for (id idView in _imagesView.subviews) {
        if([idView isKindOfClass:[UIImageView class]]){
            [idView removeFromSuperview];
        }
    }
    for (int i = 0; i < _imgArrM.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:_imgArrM[i]];
        if(i < 3){
            imageView.frame = CGRectMake(24 + (imageWidth + 24) * i, 0, imageWidth, imageWidth);
        }else{
            imageView.frame = CGRectMake(24 + (imageWidth + 24) * (i - 3), imageWidth + 16, imageWidth, imageWidth);
        }
        imageView.layer.cornerRadius = 25;
        imageView.clipsToBounds = YES;
        [_imagesView addSubview:imageView];
        imageView.userInteractionEnabled = YES;
        UIButton *delegeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [imageView addSubview:delegeBtn];
        [delegeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.top.offset(0);
            make.width.height.offset(40);
        }];
        [delegeBtn setImage:[UIImage imageNamed:@"image_delete"] forState:UIControlStateNormal];
        delegeBtn.tag = 100 + i;
        [delegeBtn addTarget:self action:@selector(delegateImg:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    if(_imgArrM.count < 3){
        [_addBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.offset((24 + imageWidth) * _imgArrM.count + 24);
            make.top.offset(0);
            make.width.height.offset(imageWidth);
        }];
    }else{
        [_addBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.offset((24 + imageWidth) * (_imgArrM.count - 3) + 24);
            make.top.offset(imageWidth  + 16);
            make.width.height.offset(imageWidth);
        }];
    }
    _titLbl.text = [NSString stringWithFormat:@"请提供问题截图（%ld/6）",_imgArrM.count];
}

-(void)textFiledEditChanged:(NSNotification*)notification{
    UITextField *textField = notification.object;
    NSString *str = textField.text;
    if(str.length > 11){
        str =  [str substringToIndex:11];
    }
    textField.text = str;
}


- (void)delegateImg:(UIButton *)sender{
    [_imgArrM removeObjectAtIndex:sender.tag - 100];
    [self updateImagesView];
}

- (void)textViewDidChange:(UITextView *)textView{
    
    if (textView.markedTextRange == nil && textView.text.length > 500) {
        textView.text = [textView.text substringToIndex:500];
    }
    _countLbl.text = [NSString stringWithFormat:@"%ld/500",textView.text.length];
}

-(void)keyboardWillShow:(NSNotification *)notification{
    WEAKSELF
    CGRect keyboardBounds;
    [[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    //拿到键盘的高度
    CGFloat keyboardHeight = keyboardBounds.size.height;
    
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        self.whireView.transform = CGAffineTransformMakeTranslation(0, -(keyboardHeight - 90));
    }];
}
 
 
//当键盘退出
-(void)keyboardWillHide:(NSNotification *)notification{
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        self.whireView.transform = CGAffineTransformIdentity;
    }];
}

-(NSMutableArray *)imgArrM{
    if(!_imgArrM){
        _imgArrM = [NSMutableArray array];
    }
    return _imgArrM;
}

@end
